#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：stock-market-analysis 
@File    ：public_methods.py
@Author  ：wrizzy
@Date    ：2025/6/16 21:20 
'''
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：pythoncode 
@File    ：public_methods.py
@Author  ：wrizzy
@Date    ：2025/6/15 22:36 
'''
import os

import pandas as pd
from openpyxl import load_workbook
from xlsxwriter import Workbook


def save_file(data,file_path,sheet_name):
    save_data = pd.DataFrame(data)
    # 如果文件已存在则加载，否则新建
    file_exists = os.path.isfile(file_path)
    # 使用ExcelWriter
    with pd.ExcelWriter(file_path, engine='openpyxl', mode='a' if file_exists else 'w') as writer:
        # 如果文件存在，加载现有工作簿
        if file_exists:
            writer.book = load_workbook(file_path)

        # 如果Sheet已存在则替换
        if sheet_name in writer.book.sheetnames:
            idx = writer.book.sheetnames.index(sheet_name)
            writer.book.remove(writer.book.worksheets[idx])
            writer.book.create_sheet(sheet_name, idx)

        # 写入数据
        data.to_excel(writer, sheet_name=sheet_name, index=False)

    print(f"数据已保存到 {file_path} 的 [{sheet_name}] Sheet页")